package com.cxy.caiapiinterface.datasource;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxy.caiapicommon.common.ErrorCode;
import com.cxy.caiapiinterface.exception.BusinessException;
import com.cxy.caiapiinterface.model.entity.Picture;
import com.cxy.caiapiinterface.model.entity.Video;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoDataSource implements DataSource<Video>{
    @Override
    public Page<Video> doSearch(String searchText, long pageNum, long pageSize) {
        String searchUrl = String.format("https://search.bilibili.com/all?keyword=%s", searchText);

        Document doc = null;
        try {
            doc = Jsoup.connect(searchUrl).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常");
        }

        Elements elements = doc.select(".bili-video-card__info--right");
        ArrayList<Video> videos = new ArrayList<>();
        Page<Video> videoPage = new Page<>(pageNum, pageSize);
        for (Element content : elements) {
            Elements a = content.select("a");
            String url = a.attr("href");
            String subUrl = url.substring(2);
            String title = a.select(".bili-video-card__info--tit").attr("title");
            Video video = new Video();
            video.setUrl(subUrl);
            video.setTitle(title);
            videos.add(video);
            if (videos.size() >= pageSize){
                videoPage.setRecords(videos);
                return videoPage;
            }
        }
        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常2");
    }
}
